package com.njcb.ams.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * zip压缩和解压工具
 * @author LOONG
 *
 */
public class AmsZipUtil {
	private static final Logger logger = LoggerFactory.getLogger(AmsZipUtil.class);
	private static final String ENCODE = "GBK";

	// 压缩
	public static void zip(String inputFilePath, String zipFileName) {
		File inputFile = new File(inputFilePath);
		if (!inputFile.exists()) {
			throw new RuntimeException("原始文件不存在!!!");
		}
		File basetarZipFile = new File(zipFileName).getParentFile();
		if (!basetarZipFile.exists() && !basetarZipFile.mkdirs()) {
			throw new RuntimeException("目标文件无法创建!!!");
		}
		BufferedOutputStream bos = null;
		FileOutputStream out = null;
		ZipOutputStream zOut = null;
		try {
			// 创建文件输出对象out,提示:注意中文支持
			out = new FileOutputStream(new String(zipFileName.getBytes(ENCODE)));
			bos = new BufferedOutputStream(out);
			// 將文件輸出ZIP输出流接起来
			zOut = new ZipOutputStream(bos);
			zip(zOut, inputFile, inputFile.getName());
			AmsIOUtils.close(zOut, bos, out);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	
	// 解压
	public static void unZip(String zipPath, String destinationPath) {
		File zipFile = new File(zipPath);
		if (!zipFile.exists()) {
			throw new RuntimeException("压缩文件" + zipPath + "不存在");
		}
	}
		
		

	private static void zip(ZipOutputStream zOut, File file, String base) {
		try {
			// 如果文件句柄是目录
			if (file.isDirectory()) {
				// 获取目录下的文件
				File[] listFiles = file.listFiles();
				// 建立ZIP条目
				zOut.putNextEntry(new ZipEntry(base + "/"));
				base = (base.length() == 0 ? "" : base + "/");
				if (listFiles != null && listFiles.length > 0) {
					for (File f : listFiles) {
						zip(zOut, f, base + f.getName());
					}
				}
			} else { // 如果文件句柄是文件
				if (base == "") {
					base = file.getName();
				}
				// 填入文件句柄
				zOut.putNextEntry(new ZipEntry(base));
				// 开始压缩 从文件入流读,写入ZIP 出流
				writeFile(zOut, file);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	private static void writeFile(ZipOutputStream zOut, File file) throws IOException {
		FileInputStream in = null;
		BufferedInputStream bis = null;
		in = new FileInputStream(file);
		bis = new BufferedInputStream(in);
		int len = 0;
		byte[] buff = new byte[2048];
		while ((len = bis.read(buff)) != -1) {
			zOut.write(buff, 0, len);
		}
		zOut.flush();
		AmsIOUtils.close(bis, in);
	}

}